<?php

namespace backend\modules\languages\controllers;

use Yii;
use yii\web\Controller;
use yii\filters\VerbFilter;
use backend\models\Clients;
use backend\models\Extensions;
use backend\modules\languages\models\searchs\Extensions as ExtensionsSearch;

class InstalledController extends Controller
{
    /**
     * {@inheritdoc}
     */
    public function behaviors()
    {
        return [
            'verbs' => [
                'class' => VerbFilter::class,
                'actions' => [
                    'switch' => ['post']
                ]
            ],
        ];
    }

    /**
     * 已安装语言列表
     * @return string
     * @throws yii\base\InvalidConfigException
     */
    public function actionIndex()
    {
        $searchModel = new ExtensionsSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

        $clientArr = Clients::getList();
        $clientList = array_map(function ($client) {
            return ucfirst($client);
        }, $clientArr);

        $languages = Extensions::findOne(['type' => 'module', 'element' => 'mod_languages']);

        if (Yii::$app->request->isPost) {
            $languagesParams = json_decode($languages->params, true);
            $post = Yii::$app->request->post();
            $languages->params = json_encode(array_merge($languagesParams, [$post['client'] => $post['code']]));
            $language = null;
            if ($languages->save()) {
                if (\common\components\Helper::getClient() === $post['client']) {
                    Yii::$app->cache->set('app.language', $post['code']);
                    $language = $post['code'];
                } else {
                    // Save original app.
                    $yiiApp = Yii::$app;

                    $configPaths = Yii::$app->params['mdm.admin.configs']['advanced'][$post['client']];
                    $config = [];
                    foreach ($configPaths as $configPath) {
                        $config = \yii\helpers\ArrayHelper::merge($config, require(Yii::getAlias($configPath)));
                    }
                    unset($config['bootstrap']);
                    $app = new \yii\web\Application($config);
                    $app->cache->set('app.language', $post['code']);
                    unset($app);
                    // Switch back to original app.
                    Yii::$app = $yiiApp;
                    unset($yiiApp);
                }

                $key = 'success';
                $msg = 'DEFAULT_LANGUAGE_SAVED';
            } else {
                $key = 'danger';
                $msg = 'DEFAULT_LANGUAGE_FAILED';
            }
            Yii::$app->session->addFlash($key, Yii::t('mod_langs', $msg, [], $language));
            return $this->refresh();
        }

        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
            'clientList' => $clientList,
            'languagesParams' => json_decode($languages->params)
        ]);
    }

    /**
     * 切换语言
     */
    public function actionSwitch()
    {
        $post = Yii::$app->request->post();
        if ($post['client'] === 'backend') {
            Yii::$app->response->cookies->add(new \yii\web\Cookie([
                'name' => 'language',
                'value' => $post['code']
            ]));
        }
        $this->redirect($post['action']);
    }
}
